<template>
  <div class="container">
    <div class="userinfo" @click="login">
      <img :src="userinfo.avatarUrl" alt="avatar">
      <p>{{ userinfo.nickName }}</p>
    </div>
    <YearProgress ></YearProgress>

    <button v-if="userinfo" @click="scanBook" class="btn"> 添加图书 </button>
  </div>
</template>

<script>
import qcloud from 'wafer2-client-sdk';
import YearProgress from '@/components/YearProgress';
import config from '@/config';
import { post, showSuccess, showFailed } from '@/utils/net';

export default {
  components: {
    YearProgress,
  },
  data() {
    return {
      userinfo: {
        avatarUrl: '/static/img/unlogin.png',
        nickName: '点击登录',
      },
    };
  },
  methods: {
    async addBook(isbn) {
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userinfo.openid,
      });

      if (res.code === 0 && res.data.title) {
        showSuccess('添加成功', `${res.data.title}添加成功`);
      };
    },
    scanBook() {
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            this.addBook(res.result);
          }
        },
      });
    },
    login() {
      const user = wx.getStorageSync('userinfo');
      if (!user) {
        qcloud.setLoginUrl(config.loginUrl);
        qcloud.login({
          success: (userinfo) => {
            console.log('登陆成功', userinfo);
            showSuccess('登陆成功'); // 模态弹窗提示
            wx.setStorageSync('userinfo', userinfo); // 本地文件存储
            this.userinfo = userinfo;
          },
          fail: (err) => {
            console.log('登陆失败', err);
            showFailed('登陆失败'); // 模态弹窗提示
          },
        });
      }
    },
    onShow() {
      const userinfo = wx.getStorageSync('userinfo');
      if (!userinfo) {
        this.userinfo = userinfo;
      }
    },
  },
  created() {
    console.log(this.userinfo);
  },
};
</script>

<style lang="scss">

.container {
  padding: 0 30rpx;
}
.userinfo {
  margin-top: 100rpx;
  text-align: center;
  img {
    width: 150rpx;
    height: 150rpx;
    margin: 20rpx;
    border-radius: 50%;
  }

}
</style>
